<?php

class model_content_category extends model
{
    
    private $categories = null;
    private $category_tree = null;

    public function get_categories()
    {
        if ($this->categories === null)
        {
            $this->categories = $this->_create_categories($this->get_category_tree());
        }
        return $this->categories;
    }

    public function get_category_sum()
    {
        $db = bone::get_db();
        return $db->get_result('SELECT COUNT(*) FROM `bone_content_category`');
    }

    public function get_category_tree()
    {
        if ($this->category_tree === null)
        {
            $db = bone::get_db();
            $categories = $db->get_objs('SELECT * FROM `bone_content_category`');
            $this->category_tree = $this->_create_categoy_tree($categories);
        }
        return $this->category_tree;
    }

    public function get_sub_category_ids($category_id)
    {
        $categories = $this->get_categories();
        
        $ids = array();
        $level = 0;
        $start = false;
        foreach ($categories as $category)
        {
            if ($start)
            {
                if ($category->level > $level)
                {
                    $ids[] = $category->id;
                }
                else
                {
                    break;
                }
            }
            else if ($category->id == $category_id)
            {
                $level = $category->level;
                $start = true;
            }
        }
        return $ids;
    }
    
    

    private function _create_categories($category_tree = null, &$categories = array())
    {
        if (count($category_tree))
        {
            foreach ($category_tree as $category)
            {
                $sub_category = null;
                if (isset($category->sub_category))
                {
                    $sub_category = $category->sub_category;
                    unset($category->sub_category);
                }
                $categories[] = $category;
                
                if ($sub_category !== null) $this->_create_categories($sub_category, $categories);
            }
        }
        return $categories;
    }

    private function _create_categoy_tree(&$categories = null, $parent_id = 0, $level = 0)
    {
        $tree = array();
        foreach ($categories as $category)
        {
            if ($category->parent_id == $parent_id)
            {
                $category->level = $level;
                $sub_category = $this->_create_categoy_tree($categories, $category->id, $level + 1);
                if (count($sub_category)) $category->sub_category = $sub_category;
                $category->children = count($sub_category);
                $tree[] = $category;
            }
        }
        return $tree;
    }

}
?>